import React, { PureComponent } from "react";
import PropTypes from "prop-types";

import { Popover, InputNumber, Button } from "antd";

class DJWeightEdit extends PureComponent {
  state = {
    value: null,
    visible: false
  };

  handleVisibleChange = visible => {
    if (visible) {
      this.setState({
        value: typeof this.props.value === "number" ? this.props.value : ""
      });
    }
    this.setState({
      visible
    });
  };

  submit = () => {
    this.setState({
      visible: false
    });
    this.props.onChange(this.state.value);
  };

  render() {
    const {
      value,
      title = "修改权重",
      loading,
      max,
      precision,
      disabled
    } = this.props;

    const content = (
      <div>
        <InputNumber
          style={{ width: "100px" }}
          defaultValue={0}
          value={this.state.value}
          onChange={value => this.setState({ value })}
          min={0}
          max={max || 999999999999}
          precision={precision || 0}
        />
        <Button
          shape="circle"
          icon="check"
          loading={loading}
          onClick={this.submit}
          disabled={this.state.value === value}
        />
        <Button
          type="danger"
          shape="circle"
          icon="close"
          onClick={() =>
            this.setState({
              visible: false
            })
          }
        />
      </div>
    );

    return !disabled ? (
      <Popover
        content={content}
        title={title}
        trigger="click"
        visible={this.state.visible}
        onVisibleChange={this.handleVisibleChange}
      >
        {this.props.children ? (
          this.props.children
        ) : (
          <a style={{ wordBreak: "normal" }} href="javascrip:;">
            {value ?? "编辑"}
          </a>
        )}
      </Popover>
    ) : this.props.children ? (
      this.props.children
    ) : (
      <a style={{ wordBreak: "normal" }} href="javascrip:;">
        {value ?? "编辑"}
      </a>
    );
  }
}

DJWeightEdit.propTypes = {
  title: PropTypes.string,
  value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
  onChange: PropTypes.func.isRequired
};

export default DJWeightEdit;
